import {useTranslation} from 'react-i18next';
import React, {
  Suspense,
  useCallback,
  useLayoutEffect,
  useMemo,
  useState,
} from 'react';
import {useRef} from 'react';
import PagerView from 'react-native-pager-view';
import {DeviceInfoProvider} from '@/components/DeviceInfo/DeviceInfoContext';
import {View} from 'react-native';
import Tab from '@/components/Tab';
import {ScrollView} from 'react-native';
import Statistics from '@/pages/OwnerMain/Statistics';
import {Card, Text, useAppTheme} from 'tsun-smart-ui';
import {AppEquipmentDTO, deviceApi, DeviceType} from '@/services/api/deviceApi';
import DeviceSkeleton from '@/components/DeviceList/DeviceSkeleton';
import store from '@/store';
import {fetchDeviceBySn, selectCurrentDevice} from '@/store/slices/deviceSlice';
import {ComponentMap} from '@/components/DeviceList';
import {useSelector} from 'react-redux';
import PageContent from '@/components/PageContent';
import {lazyLoad} from '@/utils/lazyLoad';
import {useNavigation} from '@react-navigation/native';

type InstAlarmItem = {
  message: string;
  ct: string;
  level?: number;
  code: string;
};
const Alarm = ({sn, deviceType}: {sn: string; deviceType: DeviceType}) => {
  const {t} = useTranslation();
  const theme = useAppTheme();
  const RenderItem = useCallback(({item}: {item: InstAlarmItem}) => {
    return (
      <Card className="mx-4">
        <Text className=" mb-[6]" variant="bodyStrong">
          {t(item.code)}
        </Text>
        <View className="flex-row flex-between">
          <Text
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {item.ct}
          </Text>
          <Text
            style={{
              color: theme.colors?.error?.primary,
            }}>
            {`${t('common.level')}: ${item.level}`}
          </Text>
        </View>
      </Card>
    );
  }, []);
  return (
    <PageContent
      renderItem={RenderItem}
      api={deviceApi.getAlarmList}
      params={{deviceSn: sn, deviceType}}
    />
  );
};
const fetchDeviceData = async (device: AppEquipmentDTO) => {
  await store
    .dispatch(
      fetchDeviceBySn({
        sn: device.deviceSn,
        stationId: device.stationId,
        deviceType: device.deviceType,
      }),
    )
    .unwrap();
};
export const withPromise = (Component: React.ComponentType<any>) => {
  return (props: any) => {
    return (
      <Suspense fallback={<DeviceSkeleton />}>
        <Component {...props} />
      </Suspense>
    );
  };
};
const DeviceInfo = () => {
  const [activeTab, setActiveTab] = useState('detail');
  const {t} = useTranslation();
  const navigation = useNavigation();
  const currentDevice = useSelector(selectCurrentDevice);
  const tabs = [
    {key: 'detail', title: t('common.detailBtn')},
    {key: 'statistics', title: t('pb.statistics')},
    {key: 'alert', title: t('user.alarm')},
  ];
  const paperViewRef = useRef<PagerView>(null);
  useLayoutEffect(() => {
    navigation.setOptions({
      title: currentDevice?.deviceName,
    });
  }, []);
  return (
    <DeviceInfoProvider initialDeviceData={currentDevice}>
      <View className="flex-1">
        <Tab
          tabs={tabs}
          activeKey={activeTab}
          size="small"
          onChange={(string, index) => {
            setActiveTab(string);
            paperViewRef.current?.setPage(index);
          }}
        />
        <PagerView
          style={{flex: 1, marginTop: 17}}
          onPageSelected={e => {
            setActiveTab(tabs[e.nativeEvent.position].key);
          }}
          ref={paperViewRef}>
          <View className="flex-1 " key={'detail'}>
            <ScrollView
              showsVerticalScrollIndicator={false}
              contentContainerClassName="pb-5 px-4">
              {React.createElement(
                //@ts-ignore
                ComponentMap[currentDevice?.deviceType ?? 'inv'],
              )}
            </ScrollView>
          </View>
          <View className="flex-1" key={'statistics'}>
            <Statistics></Statistics>
          </View>
          <View className="flex-1" key={'alert'}>
            <Alarm
              sn={currentDevice?.sn!}
              deviceType={currentDevice?.deviceType!}></Alarm>
          </View>
        </PagerView>
      </View>
    </DeviceInfoProvider>
  );
};
export default (props: ReactNavigation.RootStackScreenProps<'DeviceInfo'>) => {
  const AsyncDevicePage = useMemo(() => {
    return lazyLoad({
      component: DeviceInfo,
      promises: [fetchDeviceData(props.route.params)],
    });
  }, []);
  return (
    <Suspense
      fallback={
        <ScrollView contentContainerClassName="px-4 pb-4">
          <DeviceSkeleton></DeviceSkeleton>
        </ScrollView>
      }>
      <AsyncDevicePage></AsyncDevicePage>
    </Suspense>
  );
};
